package com.bigtotoro.shuiyincamera.editimage.fragment;


import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigtotoro.shuiyincamera.BaseActivity;
import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.editimage.utils.FileUtil;
import com.bigtotoro.shuiyincamera.ShowMyArtsActivity;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.editimage.EditImageActivity;
import com.bigtotoro.shuiyincamera.editimage.ModuleConfig;
import com.bigtotoro.shuiyincamera.model.RatioItem;
import com.bigtotoro.shuiyincamera.editimage.utils.Matrix3;
import com.bigtotoro.shuiyincamera.editimage.view.CropImageView;
import com.bigtotoro.shuiyincamera.editimage.view.imagezoom.ImageViewTouchBase;
import com.bigtotoro.shuiyincamera.util.MyUtils;
import com.bigtotoro.shuiyincamera.util.VideoUtil;
import com.bumptech.glide.Glide;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.microshow.rxffmpeg.RxFFmpegInvoke;
import io.microshow.rxffmpeg.RxFFmpegSubscriber;

//import VideoHandle.EpEditor;
//import VideoHandle.OnEditorListener;

/**
 * 图片去水印
 */

public class RemoveWaterMarkFragment extends BaseEditFragment {
    public static final int INDEX = ModuleConfig.INDEX_REMOVE_WATER_MARK;
    public static final String TAG = RemoveWaterMarkFragment.class.getName();
    private View mainView;
    //	private View backToMenu;// 返回主菜单
    public CropImageView mRemoveWaterMarkPanel;// 剪裁操作面板

    private RectF fatherRectf,childRectf;
    private String filePath;//原始图片路径

    private LinearLayout ratioList;
    private static List<RatioItem> dataList = new ArrayList<RatioItem>();
    static {
        // init data
        dataList.add(new RatioItem("默认", -1f));
        dataList.add(new RatioItem("1:1", 1f));
        dataList.add(new RatioItem("1:2", 1 / 2f));
        dataList.add(new RatioItem("1:3", 1 / 3f));
        dataList.add(new RatioItem("2:3", 2 / 3f));
        dataList.add(new RatioItem("3:4", 3 / 4f));
        dataList.add(new RatioItem("2:1", 2f));
        dataList.add(new RatioItem("3:1", 3f));
        dataList.add(new RatioItem("3:2", 3 / 2f));
        dataList.add(new RatioItem("4:3", 4 / 3f));
    }
    private List<TextView> textViewList = new ArrayList<TextView>();

    public static int SELECTED_COLOR = Color.YELLOW;
    public static int UNSELECTED_COLOR = Color.WHITE;
    private CropRationClick mCropRationClick = new CropRationClick();
    public TextView selctedTextView;

    public static RemoveWaterMarkFragment newInstance() {
        RemoveWaterMarkFragment fragment = new RemoveWaterMarkFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        mainView = inflater.inflate(R.layout.fragment_remove_water_mark, null);
        return mainView;
    }

    private void setUpRatioList() {
        // init UI
        ratioList.removeAllViews();
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER_VERTICAL;
        params.leftMargin = 20;
        params.rightMargin = 20;
        for (int i = 0, len = dataList.size(); i < len; i++) {
            TextView text = new TextView(activity);
            text.setTextColor(UNSELECTED_COLOR);
            text.setTextSize(20);
            text.setText(dataList.get(i).getText());
            textViewList.add(text);
            ratioList.addView(text, params);
            text.setTag(i);
            if (i == 0) {
                selctedTextView = text;
            }
            dataList.get(i).setIndex(i);
            text.setTag(dataList.get(i));
            text.setOnClickListener(mCropRationClick);
        }// end for i
        selctedTextView.setTextColor(SELECTED_COLOR);
    }

    /**
     * 选择剪裁比率
     *
     * @author
     *
     */
    private final class CropRationClick implements View.OnClickListener {  //点击监听事件
        @Override
        public void onClick(View v) {
            //如果剪裁区域不显示，让其显示
            Log.i("图片去水印","执行了====CropRationClick ");
            if (mRemoveWaterMarkPanel.getVisibility()==View.GONE){
                activity.mode = EditImageActivity.MODE_REMOVE_WATERMARK;
                activity.mRemoveWaterMarkPanel.setVisibility(View.VISIBLE);
                activity.mainImage.setImageBitmap(activity.getMainBit());
                activity.mainImage.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
                activity.mainImage.setScaleEnabled(false);// 禁用缩放
//                activity.bannerFlipper.showNext();
            }



            TextView curTextView = (TextView) v;
            selctedTextView.setTextColor(UNSELECTED_COLOR);
            RatioItem dataItem = (RatioItem) v.getTag();
            selctedTextView = curTextView;
            selctedTextView.setTextColor(SELECTED_COLOR);

            mRemoveWaterMarkPanel.setRatioCropRect(activity.mainImage.getBitmapRect(),
                    dataItem.getRatio());
        }
    }// end inner class

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        ratioList = (LinearLayout) mainView.findViewById(R.id.ratio_list_group);//1:2,1:3的菜单
        setUpRatioList();
        this.mRemoveWaterMarkPanel = ensureEditActivity().mRemoveWaterMarkPanel;

    }

    @Override
    public void onShow() {
        Log.i("图片去水印","执行了====onShow 无参");
        activity.mode = EditImageActivity.MODE_REMOVE_WATERMARK;

        activity.mRemoveWaterMarkPanel.setVisibility(View.VISIBLE);
        activity.bottomGallery.setVisibility(View.GONE);
        activity.mainImage.setImageBitmap(activity.getMainBit());
        activity.mainImage.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        activity.mainImage.setScaleEnabled(false);// 禁用缩放
        // System.out.println(r.left + "    " + r.top);
//        activity.bannerFlipper.showNext();

        //  bug  fixed  https://github.com/siwangqishiq/ImageEditor-Android/issues/59
        // 设置完与屏幕匹配的尺寸  确保变换矩阵设置生效后才设置裁剪区域
        activity.mainImage.postDelayed(new Runnable() {
            @Override
            public void run() {
                final RectF r = activity.mainImage.getBitmapRect();
                activity.mRemoveWaterMarkPanel.setCropRect(r);
            }
        },200);
//        activity.mainImage.post(new Runnable() {
//            @Override
//            public void run() {
//                final RectF r = activity.mainImage.getBitmapRect();
//                activity.mRemoveWaterMarkPanel.setCropRect(r);
//            }
//        });
    }

    @Override
    public void onShow(final EditImageActivity activity) {
        Log.i("去水印","执行了====onShow EditImageActivity");
        activity.mode = EditImageActivity.MODE_REMOVE_WATERMARK;
        filePath = EditImageActivity.filePath;

        activity.mRemoveWaterMarkPanel.setVisibility(View.VISIBLE);
        activity.bottomGallery.setVisibility(View.GONE);
        activity.mainImage.setImageBitmap(activity.getMainBit());
        activity.mainImage.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        activity.mainImage.setScaleEnabled(false);// 禁用缩放
        // System.out.println(r.left + "    " + r.top);
//        activity.bannerFlipper.showNext();

        //  bug  fixed  https://github.com/siwangqishiq/ImageEditor-Android/issues/59
        // 设置完与屏幕匹配的尺寸  确保变换矩阵设置生效后才设置裁剪区域
        activity.mainImage.postDelayed(new Runnable() {
            @Override
            public void run() {
                final RectF r = activity.mainImage.getBitmapRect();
                activity.mRemoveWaterMarkPanel.setCropRect(r);
                fatherRectf = r;//原图的坐标尺寸
//                Toast.makeText(activity, "原始rect==="+r.toString(), Toast.LENGTH_SHORT).show();
                Log.i("onshow","左="+r.left+"上="+r.top+"右="+r.right+"下="+r.bottom);
                Log.i("onshow","左="+r.left+"上="+r.top+"宽="+r.width()+"高="+r.height());
            }
        },200);
//        activity.mainImage.post(new Runnable() {
//            @Override
//            public void run() {
//                final RectF r = activity.mainImage.getBitmapRect();
//                activity.mRemoveWaterMarkPanel.setCropRect(r);
//            }
//        });
    }

    @Override
    public void onShowNoNextMenu(final EditImageActivity activity) {
        activity.mode = EditImageActivity.MODE_REMOVE_WATERMARK;

        activity.mRemoveWaterMarkPanel.setVisibility(View.VISIBLE);
        activity.mainImage.setImageBitmap(activity.getMainBit());
        activity.mainImage.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        activity.mainImage.setScaleEnabled(false);// 禁用缩放
        // System.out.println(r.left + "    " + r.top);

        //  bug  fixed  https://github.com/siwangqishiq/ImageEditor-Android/issues/59
        // 设置完与屏幕匹配的尺寸  确保变换矩阵设置生效后才设置裁剪区域
        activity.mainImage.post(new Runnable() {
            @Override
            public void run() {
                final RectF r = activity.mainImage.getBitmapRect();
                activity.mRemoveWaterMarkPanel.setCropRect(r);
            }
        });
    }

    /**
     * 返回按钮逻辑
     *
     * @author panyi
     *
     */
    private final class BackToMenuClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            backToMain();
        }
    }// end class

    /**
     * 返回主菜单
     */
    @Override
    public void backToMain() {
        Log.i("图片去水印","执行了====backToMain");
        activity.mode = EditImageActivity.MODE_NONE;
//        mRemoveWaterMarkPanel.setVisibility(View.GONE);
        activity.mainImage.setScaleEnabled(true);// 恢复缩放功能
        activity.bottomGallery.setCurrentItem(0);
        if (selctedTextView != null) {
            selctedTextView.setTextColor(UNSELECTED_COLOR);
        }
        mRemoveWaterMarkPanel.setRatioCropRect(activity.mainImage.getBitmapRect(), -1);

        getActivity().finish();
//        activity.bannerFlipper.showPrevious();
    }

    /**
     * 保存剪切图片
     */
    public void applyCropImage() {
        Log.i("图片去水印","执行了====applyCropImage");
        // System.out.println("保存剪切图片");
        CropImageTask task = new CropImageTask();
        task.execute(activity.getMainBit());
    }

    /**
     * 图片剪裁生成 异步任务
     *
     * @author panyi
     *
     */
    private final class CropImageTask extends AsyncTask<Bitmap, Void, Bitmap> {
        private Dialog dialog;
        @Override
        protected void onCancelled() {
            super.onCancelled();
            dialog.dismiss();
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        protected void onCancelled(Bitmap result) {
            super.onCancelled(result);
            Log.i("图片去水印","执行了====CropImageTask  onCancelled");

            dialog.dismiss();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.i("图片去水印","执行了====CropImageTask  onPreExecute");
            dialog = BaseActivity.getLoadingDialog(getActivity(), R.string.saving_image,
                    false);
            dialog.show();
        }

        @SuppressWarnings("WrongThread")
        @Override
        protected Bitmap doInBackground(Bitmap... params) {
            Log.i("图片去水印","执行了====CropImageTask  doInBackground");
            /**
             * 去水印,这里拿到剪裁区域的坐标
             * **/
            //应该保存整个背景的图片

//            activity.mode = EditImageActivity.MODE_NONE;
//            activity.mainImage.setImageBitmap(activity.getMainBit());// 返回原图
//            activity.mainImage.setVisibility(View.VISIBLE);
//            activity.mainImage.setScaleEnabled(true);
//            activity.bannerFlipper.showPrevious();

//            getActivity().runOnUiThread(new Runnable() {
//                public void run() {
//                    mRemoveWaterMarkPanel.setRatioCropRect(activity.mainImage.getBitmapRect(),
//                            -1);
//                }
//            });


            RectF cropRect = mRemoveWaterMarkPanel.getCropRect();// 剪切区域矩形
            Log.i("onshow","剪裁后的坐标===="+cropRect.toString());
            Log.i("onshow","左="+cropRect.left+"上="+cropRect.top+"右="+cropRect.right+"下="+cropRect.bottom);
            Log.i("onshow","左="+cropRect.left+"上="+cropRect.top+"宽="+cropRect.width()+"高="+cropRect.height());
            childRectf = cropRect;//剪裁后的坐标尺寸
            Log.i("onshow","左="+childRectf.left+"上="+childRectf.top+"右="+childRectf.right+"下="+childRectf.bottom);
            Log.i("onshow","左="+childRectf.left+"上="+childRectf.top+"宽="+childRectf.width()+"高="+childRectf.height());
            Log.i("onshow","原始图片路径===="+filePath.toString());

            Log.i("onshow","原始图片左===="+ fatherRectf.left);
            Log.i("onshow","原始图片上===="+ fatherRectf.top);
            Log.i("onshow","原始图片宽===="+ fatherRectf.width());
            Log.i("onshow","原始图片高===="+ fatherRectf.height());
            Log.i("onshow","剪裁图片宽===="+ childRectf.width());
            Log.i("onshow","剪裁图片高===="+ childRectf.height());
            Log.i("onshow","剪裁图片左坐标===="+ childRectf.left);
            Log.i("onshow","剪裁图片上坐标===="+ childRectf.top);
            /*
            * 43,560,669,874
            * 组合成坐标系(43,560),(669,560),(43,874),(669,874)
            * (L,T),(R,T),(L,B),(R,B)
            * **/
            float []l_t = {childRectf.left,childRectf.top};
            float []r_t = {childRectf.right,childRectf.top};
            float []l_b = {childRectf.left,childRectf.bottom};
            float []r_b = {childRectf.right,childRectf.bottom};

            int father_width = (int) fatherRectf.width();
            int father_height = (int) fatherRectf.height();
            int width = (int) childRectf.width()/2;
            int height = (int) childRectf.height()/2;
            int left = (int) childRectf.left - (int)fatherRectf.left;
//            int left = (int) childRectf.left  ;
            int top = (int) childRectf.top - 55 - (int)fatherRectf.top;

            //执行去水印方法
            doCropTask(filePath,father_width,father_height,width,height,left,top);
            Log.i("去水印","fatherRectf.width()===="+ fatherRectf.width());
            Log.i("去水印","fatherRectf.height()===="+ fatherRectf.height());
            Log.i("去水印","width===="+ width);
            Log.i("去水印","height===="+ height);
            Log.i("去水印","left===="+ left);
            Log.i("去水印","top===="+ top);






            //需要在矩阵转换之前传值
            Matrix touchMatrix = activity.mainImage.getImageViewMatrix();
            // Canvas canvas = new Canvas(resultBit);
            float[] data = new float[9];
            touchMatrix.getValues(data);// 底部图片变化记录矩阵原始数据
            Matrix3 cal = new Matrix3(data);// 辅助矩阵计算类
            Matrix3 inverseMatrix = cal.inverseMatrix();// 计算逆矩阵
            Matrix m = new Matrix();
            m.setValues(inverseMatrix.getValues());
            m.mapRect(cropRect);// 变化剪切矩形

            /**
             * 调用去水印方法
             * **/



            /**在这里进行图片的去水印**/
            // Paint paint = new Paint();
            // paint.setColor(Color.RED);
            // paint.setStrokeWidth(10);
            // canvas.drawRect(cropRect, paint);
            // Bitmap resultBit = Bitmap.createBitmap(params[0]).copy(
            // Bitmap.Config.ARGB_8888, true);
            Bitmap resultBit = Bitmap.createBitmap(params[0],
                    (int) cropRect.left, (int) cropRect.top,
                    (int) cropRect.width(), (int) cropRect.height());

            //saveBitmap(resultBit, activity.saveFilePath);
            return resultBit;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            dialog.dismiss();
            if (result == null)
                return;

            //这里将原始图片替换成裁剪后的图片,
//            activity.changeMainBitmap(result,true);
//            activity.mRemoveWaterMarkPanel.setCropRect(activity.mainImage.getBitmapRect());
//            backToMain();
        }
    }

    public static final String EXTRA_OUTPUT = "extra_output";
    private int imageWidth, imageHeight;
    Bitmap resultBit;
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==MSG_SUCCESS){
                Log.i("去水印保存","handleMessage");
                Toast.makeText(getActivity(), "处理完成", Toast.LENGTH_SHORT).show();
                //菜单需要变成保存
//                activity.bannerFlipper.showPrevious(); //切换菜单
                //让遮罩层消失
                if (mRemoveWaterMarkPanel.getVisibility()==View.VISIBLE){
                    activity.mode = EditImageActivity.MODE_REMOVE_WATERMARK;
                    activity.mRemoveWaterMarkPanel.setVisibility(View.INVISIBLE);


                    if (outPath != null && outPath.lastIndexOf(".") > 0) {
                        Glide.with(getActivity()).load(new File(outPath)).into(activity.mainImage);
                    }
//                    activity.mainImage.setImageBitmap(activity.getMainBit());
                    activity.mainImage.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
                    activity.mainImage.setScaleEnabled(false);// 禁用缩放

                    art.setType(0);
                    art.save();
                    DisplayMetrics metrics = getResources().getDisplayMetrics();
                    imageWidth = metrics.widthPixels; //图片原始宽高
                    imageHeight = metrics.heightPixels;
                    Intent intent = new Intent(getActivity(), ShowMyArtsActivity.class);
                    intent.putExtra(EXTRA_OUTPUT, art.getPath());
                    intent.putExtra("create_time", art.getTrueCreateTime());
                    intent.putExtra("width", imageHeight);
                    intent.putExtra("height", imageWidth);
                    intent.putExtra("type", "0");

                    FileUtil.ablumUpdate(getActivity(), art.getPath(),0);//更新相册
                    startActivity(intent);
                    getActivity().finish();

                }








//                if(mProgressDialog.isShowing()){
//                    mProgressDialog.dismiss();
//                }
            }else if(msg.what==MSG_FAIL){
                Log.i("图片去水印","执行了====mHandler  MSG_FAIL");
                Toast.makeText(getActivity(), "处理失败", Toast.LENGTH_SHORT).show();
//                if(mProgressDialog.isShowing()){
//                    mProgressDialog.dismiss();
//                }
            }else if(msg.what==MSG_PROGRESS){
//                float progress = msg.getData().getFloat("progress");
//                mProgressDialog.setProgress((int) (progress * 100));
            }else if(msg.what==MSG_CANCLE){
//                float progress = msg.getData().getFloat("progress");
//                mProgressDialog.setProgress((int) (progress * 100));
            }
        }
    };

    private static final int MSG_SUCCESS = 1;
    private static final int MSG_FAIL = 2;
    private static final int MSG_PROGRESS = 3;
    private static final int MSG_CANCLE = 4;
    private String outPath;
    private  MyArt art;
    /**图片去水印**/
    public void doCropTask(String filePath, int width, int height,
                                int rectWidth, int rectHeight, int left, int top){
        Log.i("去水印保存","执行了 doCropTask 方法");

        outPath = VideoUtil.VIDEO_SLIDE_IMAGE_DIR+"/"+System.currentTimeMillis()+".png";

        art = new MyArt();
        art.setHeight(height);
        art.setWidth(width);
        art.setCreate_time(System.currentTimeMillis()+"");
        art.setPath(outPath);//裁剪后的图片保存路径
        art.setType(0);

//        ModelSingle.getInstance().setModel(art);


        int width_01 = MyUtils.px2dip(rectWidth);
        int height_01 = MyUtils.px2dip(rectHeight);
        int width_02 = MyUtils.px2sp(rectWidth);
        int height_02 = MyUtils.px2sp(rectHeight);
        int width_03 = MyUtils.dp2px(rectWidth);
        int height_03 = MyUtils.dp2px(rectHeight);
        int width_04 = MyUtils.sp2px(rectWidth);
        int height_04 = MyUtils.sp2px(rectHeight);

        Log.i("去水印","left===="+left +"top===="+top +"left===="+top +"top===="+top);
        Log.i("去水印","rectWidth===="+rectWidth + "width_01===="+width_01+"width_02===="+width_02+"width_03===="+width_03+"width_04===="+width_04);
        Log.i("去水印","rectHeight===="+rectHeight + "height_01===="+height_01 +"height_02===="+height_02+"height_03===="+height_03+"height_04===="+height_04);

//        VideoUtil.checkVideoDir();//检查路径是否存在
//        String cmd = String.format("-i %s -filter_complex delogo=x=%d:y=%d:w=%d:h=%d:show=1 %s", filePath,left_px, top_px, rectWidth_px, rectHeight_px, out);
        String cmd = String.format("ffmpeg -i %s -filter_complex delogo=x=%d:y=%d:w=%d:h=%d:show=0 %s", filePath,left, top, rectWidth, rectHeight, outPath);
//        String cmd = String.format("-i %s -filter_complex delogo=x=300:y=300:w=100:h=100:show=1 %s", filePath, out, left, top, rectWidth, rectHeight);
//        String cmd = String.format("-i %s -filter_complex delogo=x=100:y=100:w=100:h=100:show=1 %s", filePath, out, left, top, rectWidth, rectHeight);
        int duration = VideoUtil.getDuration(getActivity(), filePath);

        Log.d(TAG, "duration "+duration);
        //FFmpeg修改

//        String text = "ffmpeg -y -i /storage/emulated/0/1/input.mp4 -vf boxblur=25:5 -preset superfast /storage/emulated/0/1/result.mp4";
        String[] commands = cmd.split(" ");
        try {
            RxFFmpegInvoke.getInstance().runCommandRxJava(commands).subscribe(new RxFFmpegSubscriber() {
                @Override
                public void onFinish() {
                    Log.i("去水印保存","EpEditor.execCmd onSuccess");
                    mHandler.sendEmptyMessage(MSG_SUCCESS);
                }

                @Override
                public void onProgress(int progress, long progressTime) {
                    Log.i("去水印保存","EpEditor.execCmd onProgress");
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putFloat("progress", progress);
                    msg.setData(data);
                    msg.what = MSG_PROGRESS;
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onCancel() {
                    Log.i("去水印保存","EpEditor.execCmd onFailure");
                    mHandler.sendEmptyMessage(MSG_CANCLE);
                }

                @Override
                public void onError(String message) {
                    Log.i("去水印保存","EpEditor.execCmd onFailure");
                    mHandler.sendEmptyMessage(MSG_FAIL);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

//        EpEditor.execCmd(cmd, duration*1000, new OnEditorListener() {
//            @Override
//            public void onSuccess() {
//                Log.i("去水印保存","EpEditor.execCmd onSuccess");
//                mHandler.sendEmptyMessage(MSG_SUCCESS);
//            }
//
//            @Override
//            public void onFailure() {
//                Log.i("去水印保存","EpEditor.execCmd onFailure");
//                mHandler.sendEmptyMessage(MSG_FAIL);
//            }
//
//            @Override
//            public void onProgress(float progress) {
//                Log.i("去水印保存","EpEditor.execCmd onProgress");
//                Message msg = new Message();
//                Bundle data = new Bundle();
//                data.putFloat("progress", progress);
//                msg.setData(data);
//                msg.what = MSG_PROGRESS;
//                mHandler.sendMessage(msg);
////                    mProgressDialog.setProgress((int) (progress * 100));
//            }
//        });
    }

    /**
     * 保存Bitmap图片到指定文件
     */
    public static void saveBitmap(Bitmap bm, String filePath) {
        File f = new File(filePath);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // System.out.println("保存文件--->" + f.getAbsolutePath());
    }
}
